import datetime
from time import sleep

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# 计算可撤销的最晚发帖日期
deadline = datetime.datetime.today() - datetime.timedelta(days=5)

url = 'https://www.52pojie.cn/home.php?mod=space&do=reward&view=me'
browser = webdriver.Chrome()
browser.get(url)

# 首次登录
next = input('登录完毕后，回车继续')
# cookies = browser.get_cookies()
# with open('d:/cookies.txt', 'w', encoding='utf-8') as f:
#     f.write(str(cookies))

# # cookie登录
# with open('d:/cookies.txt', 'r', encoding='utf-8') as f:
#     cookies = eval(f.read())
# browser.delete_all_cookies()
# for cookie in cookies:
#     browser.add_cookie(cookie)
browser.refresh()

# 获取账号id
id = browser.find_element(By.XPATH, "//div[@id='um']/p/strong/a").text

_total_page = browser.find_element(By.XPATH, '//input[@title="输入页码，按回车快速跳转"]/../span').get_attribute('title')
total_page = int(_total_page.split(' ')[1])

# 获取需要撤销的帖子信息
details = []
for page in range(total_page):
    sleep(1)      # 防止 429 Too Many Requests
    browser.get(url + '&page=' + str(page + 1))
    node_li = browser.find_elements(By.XPATH, "//ul[@class='rwdl cl']/li")
    for li in node_li:
        status = li.find_element(By.XPATH, "./div/em").text
        if status == '已解决':
            continue
        link  = li.find_element(By.XPATH, "./h4/a").get_attribute('href')
        postDate = li.find_element(By.XPATH, "./p/span").text
        # 判断帖子是否为 14 天内发布
        day = datetime.datetime.strptime(postDate, '%Y-%m-%d')
        if day > deadline:
            continue
        details.append((link, postDate))

# 打开申请撤销悬赏专帖
cancelUrl = 'https://www.52pojie.cn/thread-1875228-1-1.html'
browser.get(cancelUrl)
textarea = browser.find_element(By.XPATH, "//div[@id='fastposteditor']//textarea")
textarea.click()
# 判断当前年份
currentYear = datetime.datetime.now().year
if currentYear != 2024:
    textarea.send_keys('注意，这是 2024 年的申请撤销悬赏专贴，请复制下面内容到本年的专贴下面回复')
    textarea.send_keys(Keys.ENTER)

for det in details:
    textarea.send_keys('申请撤销CB帖子地址：' + det[0])
    textarea.send_keys(Keys.ENTER)
    textarea.send_keys('申请人ID：' + id)
    textarea.send_keys(Keys.ENTER)
    textarea.send_keys('悬赏发布时间：' + det[1])
    textarea.send_keys(Keys.ENTER)
    textarea.send_keys('申请撤销理由：' + '未解决')
    textarea.send_keys(Keys.ENTER)
    textarea.send_keys(Keys.ENTER)
# 展开评论内容，检查是否有错，修改撤销理由
browser.find_element(By.XPATH, "//div[@id='fastposteditor']/div/div/span/a").click()

next = input('''
--------------------------------
手动提交后，回车结束程序
--------------------------------
''')
